package validator;

import com.carpark.ejb.DAO.DAO;
import com.carpark.ejb.DAO.DaoImpl;
import com.carpark.ejb.Model.ClientsModel;
import com.mail.Email;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 *
 * @author Sawior
 */
@ManagedBean
@RequestScoped
public class ValidationBean implements Serializable {

    private static final long serialVersionUID = 1L;
    @Size(min = 1, max = 50, message = "Zły e-mail")
    @Pattern(regexp = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$", message = "Zły e-mail")
    private String email = null;
    @Size(min = 5, max = 255, message = "Zbyt krótkie hasło")
    private String password;
    @Size(min = 1, max = 20, message = "Wpisz imię")
    private String name = null;
    @Size(min = 1, max = 50, message = "Wpisz nazwisko")
    private String lastName = null;
    @Size(min = 1, max = 30, message = "Wpisz miasto")
    private String city;
    @Size(min = 1, max = 15, message = "Wpisz kod pocztowy")
    private String zipCode;
    @Size(min = 1, max = 30, message = "Wpisz ulicę")
    private String street;
    @Size(min = 1, max = 15, message = "Wpisz numer domu")
    private String houseNumber;
    private Integer localNumber;
    @Size(min = 0, max = 13, message = "Zły numer lokalu")
    private String nipNumber;
    @Size(min = 0, max = 12, message = "Podaj telefon")
    private String phone;
    @AssertTrue(message = "Wymagane do rejestracji")
    private boolean agreed = true;
    private final DAO dao = new DaoImpl();

    public String registry() throws NamingException {
        String passwordAfterCode;
        try {
            passwordAfterCode = codePassword();
        } catch (NoSuchAlgorithmException ex) {
            createErrorMessage("");
            Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] MD5 exception, no such algorithm.", ex);
            return "/register.xhtml";
        }
        createClient(passwordAfterCode);
        Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "Adding new record to database.");
        Email email = new Email(this.email, "car20park13", "Dane po rejestracji", "Witaj. Dziękujemy za rejestrację. Możesz zalogować się na naszą stronę używając adresu email.");
        try {
            email.send();
        } catch (Exception ex) {
            Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] Mail not sended - exception during sending.", ex);
        }

        return "/afterRegistration.xhtml";
    }

    private String codePassword() throws NoSuchAlgorithmException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte byteData[] = md.digest();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }

    private void createErrorMessage(String text) {
        FacesMessage msg = new FacesMessage();
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        msg.setSummary("Wystąpił błąd podczas rejestracji. " + text);
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    private void createClient(String passwordAfterCode) {
        if (isEmailOccupied(email)) {
            createErrorMessage("Podany email jest zajęty. Skorzystaj z przypomnienia hasła");
        } else {
            dao.addClient(new ClientsModel(name, lastName, city, zipCode, street, houseNumber, localNumber, nipNumber, phone, email, passwordAfterCode));
        }
    }

    private boolean isEmailOccupied(String email) {
        return dao.getClientByEmail(email) != null;
    }

    public boolean isAgreed() {
        return agreed;
    }

    public void setAgreed(boolean agreed) {
        this.agreed = agreed;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getHouseNumber() {
        return houseNumber;
    }

    public void setHouseNumber(String houseNumber) {
        this.houseNumber = houseNumber;
    }

    public Integer getLocalNumber() {
        return localNumber;
    }

    public void setLocalNumber(Integer localNumber) {
        this.localNumber = localNumber;
    }

    public String getNipNumber() {
        return nipNumber;
    }

    public void setNipNumber(String nipNumber) {
        this.nipNumber = nipNumber;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String registryM() throws NamingException {
        String passwordAfterCode;
        try {
            passwordAfterCode = codePassword();
        } catch (NoSuchAlgorithmException ex) {
            createErrorMessage("");
            Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] MD5 exception, no such algorithm.", ex);
            return "/register.xhtml";
        }
        createClient(passwordAfterCode);
        Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "Adding new record to database.");
     
        try {
      
        } catch (Exception ex) {
            Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] Mail not sended - exception during sending.", ex);
        }
        Logger.getLogger(ValidationBean.class.getName()).log(Level.SEVERE, "[CarPark] Mobile redirect");
        return "pm:sc";
    }
}
